package com.doit.demo.day01;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSink;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

/**
 * @DATE 2022/2/26/17:48
 * @Author MDK
 * @Version 2021.2.2
 **/

//自定义Sink实现与printSink一样的功能
public class MyPrintSink {
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        //设置固定端口号
        configuration.setInteger("rest.port",8081);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);

        int parallelism = env.getParallelism();
        System.out.println("当前环境中的并行度:"+parallelism);

        //获取算子所在的task的并行度(获取对应的DataStream所在的并行度)
        //SocketSource即socketTextStream创建的DataStream的并行度永远是1
        DataStreamSource<String> lines = env.socketTextStream("linux01", 8888);
        int parallelism1 = lines.getParallelism();
        System.out.println("SocketSource对应的DataStream并行度为:" + parallelism1);

        //map是多并行的算子,如果没有指定该算子并行度,默认与执行环境的并行度一致
        SingleOutputStreamOperator<String> upperStream = lines.map(new MapFunction<String, String>() {
            @Override
            public String map(String line) throws Exception {
                return line.toUpperCase();
            }
        }).setParallelism(2);

        //获取map算子对应的Task的并行度
        int parallelism2 = upperStream.getParallelism();
        System.out.println("map算子所在的task并行度:" + parallelism2);

        //调用sink
        DataStreamSink<String> streamSink = upperStream.addSink(new RichSinkFunction<String>() {
            @Override
            public void invoke(String value, Context context) throws Exception {
                System.out.println(getRuntimeContext().getIndexOfThisSubtask() + ">" + value);
            }
        });

        System.out.println("sink算子所在subtask并行度为:"+streamSink.getTransformation().getParallelism());

        env.execute();


    }
}
